"""
便捷脚本，用来自动生成markdown文档、数据库sql
"""
import os
import sys
import django
from django.db import models

sys.path.append("../apps/")
sys.path.append("../")
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
    django.setup()


def create_tapd(model, app_db: str = 'curriculum', enum=None, not_need_field=None, auto_field=None):
    """
    生成TAPD文档：表结构、参数说明以及mysql的创建脚本
    :param model: 对应的模型
    :param app_db: mysql的数据库的名称
    :param enum: 数据库的枚举类型
    :param not_need_field: 可以不传递的参数
    :param auto_field: 由后端自动生成的参数哦
    :return:
    """
    if enum is None:
        enum = {}
    if not_need_field is None:
        not_need_field = []
    if auto_field is None:
        auto_field = []

    model_help = model.__doc__.strip()
    print(f"### {model_help}\n")
    print("#### 表结构\n")
    print("||~字段||~字段类型||~字段含义||~必传/是否需要传递||")
    for field in model._meta.fields:
        if field.name == 'id':
            print("|| id || 自增整形主键 || 主键  || 否 ||")
            continue
        name, help_text = field.name, field.help_text
        if field.choices is not None:
            help_text = help_text + ';' + '、'.join([f'{o[0]}: {o[1]}' for o in field.choices])
        if isinstance(field, models.CharField) or isinstance(field, models.TextField):
            kind = "字符串"
        elif isinstance(field, models.IntegerField) or isinstance(field, models.SmallIntegerField):
            kind = "整形"
        elif isinstance(field, models.FloatField):
            kind = "浮点型"
        elif isinstance(field, models.DecimalField):
            kind = "金额"
        elif isinstance(field, models.DateTimeField):
            kind = "时间"
        elif isinstance(field, models.DateField):
            kind = "日期"
        elif isinstance(field, models.ForeignKey):
            kind = "整形"
        else:
            raise
        if field.name in not_need_field:
            if type(field.default) != type:
                print(f"|| {name} || {kind} || {help_text}  || 可以不传递，默认值为：{field.default} ||")
            else:
                print(f"|| {name} || {kind} || {help_text}  || 可以不传递 ||")
        elif field.name in auto_field:
            if type(field.default) != type:
                print(f"|| {name} || {kind} || {help_text}  || 不需要传递，由后端生成，默认值为：{field.default} ||")
            else:
                print(f"|| {name} || {kind} || {help_text}  || 不需要传递，由后端生成 ||")
        else:
            if type(field.default) != type:
                print(f"|| {name} || {kind} || {help_text}  || 默认值为：{field.default}，必传 ||")
            else:
                print(f"|| {name} || {kind} || {help_text}  || 是 ||")

    sql = """
create table {}
(
    id         int auto_increment primary key,
    {}
);
        """
    sql_field = []
    for field in model._meta.fields:
        if field.name == 'id':
            continue
        name, help_text = field.name, field.help_text
        if field.choices is not None:
            help_text = help_text + ';' + '、'.join([f'{o[0]}: {o[1]}' for o in field.choices])
        if isinstance(field, models.CharField):
            if field.name in enum:
                enum_f = ','.join(enum[field.name][0])
                enum_d = enum[field.name][1]
                sql_field.append(f"    {field.name} enum({enum_f}) default '{enum_d}' not null")
                continue
            if field.choices is not None:
                if type(field.default) == type:
                    sql_field.append(f"    {name} char({field.max_length})  not null comment '{help_text}'")
                else:
                    sql_field.append(
                        f"    {name} varchar({field.max_length}) default '{field.default}'  not null comment '{help_text}'")
            else:
                if type(field.default) == type:
                    sql_field.append(f"    {name} varchar({field.max_length})  not null comment '{help_text}'")
                else:
                    sql_field.append(
                        f"    {name} varchar({field.max_length}) default '{field.default}'  not null comment '{help_text}'")
        elif isinstance(field, models.TextField):
            if type(field.default) == type:
                sql_field.append(f"    {field.name} longtext not null comment '{help_text}'")
            else:
                sql_field.append(
                    f"    {field.name} longtext default '{field.default}' not null comment '{help_text}'")
        elif isinstance(field, models.IntegerField):
            if type(field.default) == type:
                sql_field.append(f"    {field.name} int not null comment '{help_text}'")
            else:
                sql_field.append(
                    f"    {field.name} int default {field.default} not null comment '{help_text}'")
        elif isinstance(field, models.SmallIntegerField):
            if type(field.default) == type:
                sql_field.append(f"    {field.name} smallint not null comment '{help_text}'")
            else:
                sql_field.append(
                    f"    {field.name} smallint default {field.default} not null comment '{help_text}'")
        elif isinstance(field, models.DecimalField):
            if type(field.default) == type:
                sql_field.append(
                    f"    {field.name} numeric({field.max_digits},{field.decimal_places}) not null comment '{help_text}'")
            else:
                sql_field.append(
                    f"    {field.name} numeric({field.max_digits},{field.decimal_places}) default '{field.default}' not null comment '{help_text}'")
        elif isinstance(field, models.DateTimeField):
            sql_field.append(f"    {field.name} datetime not null comment '{help_text}'")
        elif isinstance(field, models.DateField):
            sql_field.append(f"    {field.name} date not null comment '{help_text}'")
        elif isinstance(field, models.ForeignKey):
            sql_field.append(f"    {field.name}_id int not null comment '{help_text}'")
        elif isinstance(field, models.FloatField):
            if type(field.default) == type:
                sql_field.append(f"    {field.name} int not null comment '{help_text}'")
            else:
                sql_field.append(
                    f"    {field.name} float default {field.default} not null comment '{help_text}'")
        else:
            raise
    sql_field[0] = sql_field[0].strip()
    sql = sql.format(app_db, ',\n'.join(sql_field))
    print("#### 创建表结构")
    print("```")
    print(sql)
    print("```")


if __name__ == '__main__':
    pass
